package com.sena.engine.snmp.handler;

import com.sena.engine.common.exception.SenaSnmpRunTimeException;
import com.sena.engine.snmp.utils.SnmpUtils;
import net.percederberg.mibble.MibValueSymbol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.Variable;
import org.snmp4j.smi.VariableBinding;

import java.util.List;

/**
 * @author Admin
 */
public class RefreshHandler {

    private static final Logger log = LoggerFactory.getLogger(RefreshHandler.class);

    public void reFresh(Object obj, Snmp snmp, Target target) throws SenaSnmpRunTimeException {
        try {
            String oid = SnmpUtils.getMibOIDofClass(obj.getClass());
            MibValueSymbol mibValueSymbol = SnmpUtils.getMibSymbolByOid(oid);
            String mappingOID = SnmpUtils.getTableOrGroupIndexOID(obj, mibValueSymbol);
            Class clazz = obj.getClass();
            List list = SnmpUtils.getFieldsInMibNode(clazz, mibValueSymbol);
            //udp根据版本创建
            PDU pdu = SnmpUtils.createPdu(target.getVersion());
            for (int i = 0; i < list.size(); i++) {
                MibValueSymbol symbol = (MibValueSymbol) list.get(i);
                String str = symbol.getValue().toString() + "." + mappingOID;
                pdu.add(new VariableBinding(new OID(str)));
            }
            ResponseEvent responseEvent = snmp.get(pdu, target);
            SnmpUtils.checkSnmpError(responseEvent);
            List events = responseEvent.getResponse().getVariableBindings();
            for (int i = 0; i < events.size(); i++) {
                VariableBinding variableBinding = (VariableBinding) events.get(i);
                String oidStr = variableBinding.getOid().toString();
                String name = mibValueSymbol.getMib().getSymbolByOid(oidStr).getName();
                Variable value = variableBinding.getVariable();
                if (value.toString().equalsIgnoreCase("noSuchObject")) {
                    throw new SenaSnmpRunTimeException(",设备IP:" + name);
                }
                SnmpUtils.setFieldValue(obj, name, value);
            }
        } catch (Exception e) {
            String msg = "从设备中获取对象出错,对象:" + obj.getClass().getName() + ",设备IP:" + target.getAddress() + "错误" + e.getMessage();
            throw new SenaSnmpRunTimeException(msg);
        }
    }
}
